package com.abner.basis.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程之间进行通信
 * 两个线程操作同一个变量,对变量进行加减操作
 *
 * @Author yuhui
 * @Date: 2024/3/19
 */
public class ThreadLockComm {
    public static void main(String[] args) {
        ShareRes share = new ShareRes();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "D").start();
    }
}

class ShareRes {
    private int num = 0;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    /**
     * 加1
     */
    public void incr() throws InterruptedException {
        lock.lock();
        try {
            while (num != 0) {
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName() + "进行加1操作,计算后的结果为: " + num);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    /**
     * 减1
     */
    public void decr() throws InterruptedException {

        lock.lock();
        try {
            while (num != 1) {
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName() + "进行减1操作,计算后的结果为: " + num);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

}
